/**
 * 时间格式化
 * @param {number} time - 时间，单位秒
 * @returns {string} 格式化后的时间字符串 (mm:ss)
 */
export const formatTime = (time) => {
  if (!time) return '00:00'
  
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

/**
 * 数字格式化
 * @param {number} num - 需要格式化的数字
 * @returns {string} 格式化后的字符串
 */
export const formatNumber = (num) => {
  if (!num) return '0'
  
  if (num >= 100000000) {
    return (num / 100000000).toFixed(1) + '亿'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

/**
 * 解析歌词文本
 * @param {string} lrcText - 歌词文本
 * @returns {Array} 解析后的歌词数组
 */
export const parseLyric = (lrcText) => {
  const lines = lrcText.split('\n')
  const lyrics = []
  const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/

  lines.forEach(line => {
    const match = timeRegex.exec(line)
    if (match) {
      const minutes = parseInt(match[1])
      const seconds = parseInt(match[2])
      const milliseconds = parseInt(match[3])
      const text = match[4].trim()
      
      const time = minutes * 60 + seconds + milliseconds / 1000
      if (text && !text.includes('：')) {
        lyrics.push({ time, text })
      }
    }
  })

  return lyrics.sort((a, b) => a.time - b.time)
}

/**
 * 获取当前播放时间对应的歌词索引
 * @param {Array} lyrics - 歌词数组
 * @param {number} currentTime - 当前播放时间（秒）
 * @returns {number} 当前歌词的索引
 */
export const findLyricIndex = (lyrics = [], currentTime = 0) => {
  for (let i = lyrics.length - 1; i >= 0; i--) {
    if (currentTime >= lyrics[i].time) {
      return i
    }
  }
  return 0
}